<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>
      <!-- 登录表单 -->
      <el-form :model="formData" :rules="formDataRule" ref="fordataRef">
        <el-form-item label="账号" prop="username">
          <el-input
            placeholder="请输入账号"
            v-model="formData.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="formData.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="doLogin">登陆</el-button>
          <el-button type="danger" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { uesrLogin } from '@/api/user.js'
export default {
  name: 'login-page',
  data() {
    return {
      formData: {
        username: '',
        password: '',
      },
      formDataRule: {
        username: [
          {
            required: true,
            // 出错提升信息
            message: '用户名不能为空',
            // 触发类型
            trigger: 'blur',
          },
          {
            pattern: /^\w{5,11}$/,
            // 出错提升信息
            message: '用户名为5-11位',
            // 触发类型
            trigger: 'blur',
          },
        ],
        password: [
          {
            // 必须
            required: true,
            // 出错提升信息
            message: '密码不能为空',
            // 触发类型
            trigger: 'blur',
          },
          {
            // 必须
            pattern: /^\w{5,11}$/,
            // 出错提升信息
            message: '密码为5-11位',
            // 触发类型
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    doLogin() {
      this.$refs.fordataRef.validate(async (valid) => {
        if (valid) {
          const { data } = await uesrLogin(this.formData)
          //提交mutation更新state
          this.$store.commit('user/upDataToken', data.token)
          //轻提示
          this.$message.success('登陆成功')
          // 跳转
          this.$router.push('/')
        } else {
          this.$message.warning('用户名或密码错误')
        }
      })
    },
    doReset() {
      this.formData.username = ''
      this.formData.password = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header {
      text-align: center;
      background-color: skyblue;
      height: 60px;
      color: white;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
